package com.qingke.note.command_impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.ibatis.session.SqlSession;

import com.qingke.note.Console;
import com.qingke.note.IDao.LabelMapper;
import com.qingke.note.IDao.NoteMapper;
import com.qingke.note.command.Command;
import com.qingke.note.pojo.Label;
import com.qingke.note.pojo.Note;
import com.qingke.note.pojo.User;

public class DeleteCommand extends Command {

	public DeleteCommand(User user) {
		super(user);
	}

	@Override
	public void execute() {
		
		if(currentUser==null){
			Console.println("您还未登录，不能执行此操作");
			return;
		}
		Console.println("【1】删除备忘");
		Console.println("【2】删除标签");
		int choice = Console.askInputInt("请输入操作序号");
		
		while(true){
			if(choice==1){
				delNote();
			}else if(choice==2){
				delLabel();
			}else {
				choice = Console.askInputInt("输入不正确，请重新输入");
				continue;
			}
			return;
		}
		
	}
	
	private void delLabel() {
		SqlSession session = getSession();
		LabelMapper labelMapper = session.getMapper(LabelMapper.class);		
		List<Note> notes = currentUser.getNotes();
		Set<Label>  labs = new HashSet<Label>();
		List<Label> labels = new ArrayList<Label>(labs);
		for (Note note : notes) {
			labs.add(note.getLabel());
		}
		int index =1;
		for (Label label : labs) {
			Console.print("【"+index+"】");
			Console.println(label);
			index++;
		}
		
		int choice = Console.askInputInt("请输入要删除的标签序号") - 1;
		while(true){
			if(choice>=index){
				Console.println("序号不存在");
				choice = Console.askInputInt("请重新输入要删除的标签序号");
				continue;
			}
			labels.get(index).setEffective("N");
			labelMapper.updateByPrimaryKeySelective(labels.get(index));
			session.commit();
			Console.println("标签已成功删除");
			session.close();
			
		}	
	}

	private void delNote(){
		ListCommand listCommand = new ListCommand(currentUser);
		SqlSession session = getSession();
		NoteMapper noteMapper = session.getMapper(NoteMapper.class);
		listCommand.execute();
		if(listCommand.printed==0){
			return;
		}
		int index = Console.askInputInt("要删除的备忘序号")-1;
		while(true){
			if(index>=listCommand.printed){
				Console.println("序号不存在");
				index = Console.askInputInt("请重新输入要删除的备忘序号");
				continue;
			}
			currentUser.getNotes().get(index).setEffective("N");
			noteMapper.updateByPrimaryKeySelective(currentUser.getNotes().get(index));
			session.commit();
			Console.println("备忘已成功删除");
			session.close();
		}
	}

}
